import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Dimensions,
  Image,
  Modal,
  ActivityIndicator,
  Alert,
  Platform,
  StatusBar,
  TouchableWithoutFeedback,
} from "react-native";
import React, { useState, useRef, useEffect, useContext } from "react";
import ImageViewer from "react-native-image-zoom-viewer";
import VideoPlayer from "expo-video-player";
import { Audio } from "expo-av";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import Icon from "@expo/vector-icons/Entypo";
import { Feather } from "@expo/vector-icons";
import { MaterialIcons } from "@expo/vector-icons";
import { ResizeMode } from "expo-av";
import { Tabs, MaterialTabBar } from "react-native-collapsible-tab-view";
import AsyncStorage from "@react-native-async-storage/async-storage";
import InterviewContext from "../../context/interview/InterviewContext";
import LoadingBar from "../../components/InterView/LoadingBar";
import AudioListItemNodelete from "../../components/InterView/AudioListItemNodelete";
import { play, pause, resume, playNext } from "../../utils/audioController";
import { fileWeb } from "../../api/query";
import NoData from "../../components/InterView/NoData";

const { width: DEVICE_WIDTH, height: DEVICE_HEIGHT } = Dimensions.get("window");

const Loading = () => {
  return (
    <View>
      <ActivityIndicator animating={true} size={"large"} />
    </View>
  );
};

const InterviewDetail = ({ route, navigation }) => {
  //判断role,查看是管理员还是调查员，看是否渲染编辑/删除按钮
  const { _id } = route.params;
  const { interviewList, deleteInterviewAndBack } =
    useContext(InterviewContext);

  //传来的interview数据
  const [dataDetail, setDataDetail] = useState({
    _id: "",
    fileName: "",
    type: "",
    provincekey: "",
    citykey: "",
    areakey: "",
    province: "",
    city: "",
    area: "",
    address: "",
    latitude: "",
    longitude: "",
    municipalLeaders: 0,
    municipalDepartment: 0,
    countyLeaders: 0,
    countyDepartment: 0,
    townshipLeaders: 0,
    villageCadres: 0,
    villageDoctorsAndPrincipals: 0,
    firstSecretary: 0,
    NPCdeputies: 0,
    interviewImageList: [],
    interviewAudioList: [],
    interviewVideoList: [],
    time: "",
    publisher: "",
  });
  const [inFullscreen, setInFullsreen] = useState(false);
  //放大图片
  const [magnifypVisible, setMagnifypVisible] = useState(false);
  const [index, setIndex] = useState(0);
  const [imagesUrl, setimagesUrl] = useState([]);
  //保存图片/视频权限
  const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState();
  //编辑删除Modal可见性
  const [isVisible, setIsVisible] = useState(false);
  //控制编辑删除Modal偏移量 距离上方多少
  const [topOffset, setTopOffset] = useState(0);
  //加载
  const [isLoading, setIsLoading] = useState(false);
  const refVideo = useRef(null);
  let positionMark = useRef();

  const [currentAudio, setCurrentAudio] = useState({});
  const [currentAudioIndex, setCurrentAudioIndex] = useState(null);
  const [soundObj, setSoundObj] = useState(null);
  const [playbackObj, setPlaybackObj] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [role, setRole] = useState();

  useEffect(() => {
    let isMounted = true;
    if (isMounted) {
      setIsLoading(true);
      //判断是否有编辑/删除按钮
      getRole();
      //渲染数据
      const singleInterview = interviewList.filter((item) => item._id === _id);
      if (singleInterview.length != 0) {
        setDataDetail(singleInterview[0]);
      }
      setIsLoading(false);
      //获得访问媒体库权限
      getPermission();
    }
    return () => {
      isMounted = false;
    };
  }, [interviewList]);

  const getPermission = async () => {
    const permission = await MediaLibrary.getPermissionsAsync();
    if (permission.granted) {
      setHasMediaLibraryPermission(true);
    }
    if (!permission.granted && permission.canAskAgain) {
      const { status, canAskAgain } =
        await MediaLibrary.requestPermissionsAsync();
      if (status === "granted") {
        setHasMediaLibraryPermission(true);
      }
      if (status === "denied" && canAskAgain) {
        permissionAllert();
      }
      if (status === "denied" && !canAskAgain) {
        alert("未授权访问媒体库的权限，请在设置中进行修改");
      }
    }
    if (!permission.canAskAgain && !permission.granted) {
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const getRole = async () => {
    const role = await AsyncStorage.getItem("role");
    setRole(role);
  };

  const permissionAllert = () => {
    Alert.alert("权限请求", "本App需要读取系统媒体库的权限", [
      {
        text: "允许",
        onPress: () => getPermission(),
      },
      {
        text: "不允许",
        onPress: () => alert("未授权访问媒体库的权限，请在设置中进行修改"),
      },
    ]);
  };

  const saveImage = async (item) => {
    setIsLoading(true);
    let url = item.url;
    const localpicture = await FileSystem.downloadAsync(
      url,
      FileSystem.documentDirectory + item.name
    );
    if (localpicture.status != 200) {
      setIsLoading(false);
      alert("下载失败！");
    } else {
      url = localpicture.uri;
    }

    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          setIsLoading(false);
          alert("已保存到系统相册");
        });
      } catch (error) {
        setIsLoading(false);
        alert("保存时出错了！");
      }
    } else {
      setIsLoading(false);
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const saveResoure = async (item) => {
    setIsLoading(true);
    let url = fileWeb + "/" + item.filePath;
    const localurl = await FileSystem.downloadAsync(
      url,
      FileSystem.documentDirectory + item.fileName
    );
    if (localurl.status != 200) {
      setIsLoading(false);
      alert("下载失败！");
    } else {
      url = localurl.uri;
    }

    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          setIsLoading(false);
          alert("已保存到系统文件");
        });
      } catch (error) {
        setIsLoading(false);
        alert("保存时出错了！");
      }
    } else {
      setIsLoading(false);
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const saveVideoAlert = (video) => {
    Alert.alert("提示", "要保存这个视频吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          saveResoure(video);
        },
      },
    ]);
  };

  //编辑/删除Modal位置信息
  const showModal = () => {
    positionMark.current.measure((x, y, width, height, pageX, pageY) => {
      //Android的Y轴坐标是从状态栏以下开始计算的，而屏幕高度是包含了状态栏在内的,因此需要减去相应的高度
      // iOS是从屏幕顶端开始计算的
      const AndroidStatusBar =
        Platform.OS === "android" ? StatusBar.currentHeight : 0;
      const topOffset = pageY + height - AndroidStatusBar; // 计算"筛选"距离页面顶部的偏移量
      setTopOffset(topOffset);
    });
  };

  //删除整个数据
  const deleteData = () => {
    Alert.alert("提示", "确定删除吗?", [
      {
        text: "取消",
        onPress: () => {
          setIsVisible(false);
        },
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          setIsVisible(false);
          setIsLoading(true);
          deleteInterviewAndBack(
            dataDetail,
            () => {
              setIsLoading(false);
            },
            () => {
              navigation.goBack();
            }
          );
        },
      },
    ]);
  };

  //处理录音点击事件
  const handleAudioPress = async (audio) => {
    const index = dataDetail.interviewAudioList.indexOf(audio);
    // playing audio for the first time.
    if (soundObj === null) {
      const playbackObj = new Audio.Sound();
      const status = await play(playbackObj, fileWeb + "/" + audio.filePath);
      setCurrentAudio(audio);
      setCurrentAudioIndex(index);
      setIsPlaying(true);
      setPlaybackObj(playbackObj);
      setSoundObj(status);

      playbackObj.setOnPlaybackStatusUpdate((playbackStatus) => {
        if (playbackStatus.didJustFinish) {
          setCurrentAudio({});
          setCurrentAudioIndex(null);
          setIsPlaying(false);
          setPlaybackObj(null);
          setSoundObj(null);
        }
      });
    } else {
      // pause audio
      if (
        soundObj.isLoaded &&
        soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await pause(playbackObj);
        setSoundObj(status);
        setIsPlaying(false);
      }
      // resume audio
      if (
        soundObj.isLoaded &&
        !soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await resume(playbackObj);
        setSoundObj(status);
        setIsPlaying(true);
      }
      // select another audio
      if (soundObj.isLoaded && index !== currentAudioIndex) {
        const status = await playNext(
          playbackObj,
          fileWeb + "/" + audio.filePath
        );
        setCurrentAudio(audio);
        setSoundObj(status);
        setIsPlaying(true);
        setCurrentAudioIndex(index);
      }
    }
  };

  const Header = () => {
    return (
      <View style={styles.topContainer}>
        <LoadingBar visible={isLoading} />

        {/* 编辑和删除Modal */}
        {isVisible ? (
          <View style={styles.ModalBackground}>
            <Modal animationType="fade" transparent={true}>
              <TouchableWithoutFeedback onPress={() => setIsVisible(false)}>
                <View style={{ height: topOffset }}></View>
              </TouchableWithoutFeedback>
              <View style={[styles.bubblePosition, { top: topOffset + 10 }]}>
                <View style={styles.bubbleModal}>
                  <View style={styles.triangle} />
                  <View style={styles.rectangle}>
                    <TouchableOpacity
                      style={styles.rectangleItem}
                      onPress={() => {
                        setIsVisible(false);
                        navigation.navigate("InterviewEdit", {
                          editData: dataDetail,
                        });
                      }}
                    >
                      <MaterialIcons
                        name="mode-edit"
                        size={24}
                        color="#b3b3b3"
                      />
                      <Text style={styles.rectangleText}>编辑</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                      style={styles.rectangleItem}
                      onPress={() => {
                        deleteData();
                      }}
                    >
                      <MaterialIcons
                        name="delete-outline"
                        size={25}
                        color="#b3b3b3"
                      />
                      <Text style={styles.rectangleText}>删除</Text>
                    </TouchableOpacity>
                  </View>
                </View>
              </View>
              <TouchableWithoutFeedback onPress={() => setIsVisible(false)}>
                <View style={{ flex: 1 }}></View>
              </TouchableWithoutFeedback>
            </Modal>
          </View>
        ) : null}

        <View
          style={{
            flex: 1,
            flexDirection: "column",
            justifyContent: "space-between",
            marginBottom: 30,
          }}
        >
          {/* 头部 */}
          <View style={[styles.head]}>
            {/* 返回按钮 */}
            <TouchableOpacity
              onPress={() => {
                navigation.goBack();
              }}
              style={{ width: "50%" }}
            >
              <Icon name="chevron-left" size={24} color="#044244" />
            </TouchableOpacity>
            {/* 编辑和删除按钮 */}
            {role === "user" ? (
              <TouchableOpacity
                ref={positionMark}
                onPress={() => {
                  setIsVisible(!isVisible);
                  showModal();
                }}
                style={{ width: "50%", alignItems: "flex-end" }}
              >
                <Icon name="dots-two-vertical" size={24} color="#044244" />
              </TouchableOpacity>
            ) : null}
          </View>
          {/* 文件名、类型、地址 */}
          <View>
            <Text style={styles.fileName}>{dataDetail.fileName}</Text>
            <Text style={styles.fileType}>{dataDetail.type}</Text>
            {dataDetail.province == "" &&
            dataDetail.city == "" &&
            dataDetail.area == "" &&
            dataDetail.address == "" ? (
              <Text style={styles.fileType}>暂未填写地址信息</Text>
            ) : (
              <Text style={styles.fileType}>
                {dataDetail.province}
                {dataDetail.city}
                {dataDetail.area}
                {dataDetail.address}
              </Text>
            )}
          </View>
          {/* 座谈访谈人次 */}
          <View
            style={{
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            {/* 第一行 */}
            <View style={styles.firstrowStyle}>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>
                  {dataDetail.municipalLeaders}人
                </Text>
                <Text style={styles.tagText}>市级领导</Text>
              </View>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>
                  {dataDetail.municipalDepartment}人
                </Text>
                <Text style={styles.tagText}>市级行业部门</Text>
              </View>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>
                  {dataDetail.countyLeaders}人
                </Text>
                <Text style={styles.tagText}>县级领导</Text>
              </View>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>
                  {dataDetail.countyDepartment}人
                </Text>
                <Text style={styles.tagText}>县级行业部门</Text>
              </View>
            </View>
            {/* 第二行 */}
            <View style={styles.rowStyle}>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>
                  {dataDetail.townshipLeaders}人
                </Text>
                <Text style={styles.tagText}>乡镇干部</Text>
              </View>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>
                  {dataDetail.villageDoctorsAndPrincipals}人
                </Text>
                <Text style={styles.tagText}>村医、小学校长</Text>
              </View>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>
                  {dataDetail.villageCadres}人
                </Text>
                <Text style={styles.tagText}>村干部</Text>
              </View>
            </View>
            {/* 第三行 */}
            <View style={styles.rowStyle}>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>
                  {dataDetail.firstSecretary}人
                </Text>
                <Text style={styles.tagText}>第一书记或驻村工作队</Text>
              </View>
              <View style={styles.rowItem}>
                <Text style={styles.tagCount}>{dataDetail.NPCdeputies}人</Text>
                <Text style={styles.tagText}>人大代表和政协委员</Text>
              </View>
            </View>
          </View>
        </View>
      </View>
    );
  };

  const TabBarComponent = (props) => {
    return (
      <MaterialTabBar
        {...props}
        activeColor="#A80108"
        inactiveColor="#000000"
        inactiveOpacity={1}
        height={70}
        labelStyle={{
          fontSize: 15,
        }}
        style={{
          paddingTop:
            Platform.OS == "android" ? StatusBar.currentHeight - 10 : 0,
        }}
      />
    );
  };

  return (
    <Tabs.Container renderHeader={Header} renderTabBar={TabBarComponent}>
      <Tabs.Tab name="访谈图片">
        <Tabs.ScrollView
          style={{ backgroundColor: "#FFFFFF" }}
          showsVerticalScrollIndicator={false}
        >
          {dataDetail.interviewImageList.length != 0 ? (
            <View style={styles.imageList}>
              {dataDetail.interviewImageList.map((image, index) => {
                return (
                  <View key={index}>
                    {/* 图片列表，点击放大 */}
                    <TouchableOpacity
                      onPress={() => {
                        var newimageList = dataDetail.interviewImageList.map(
                          (item) => ({
                            name: item.fileName,
                            url: fileWeb + "/" + item.filePath,
                            props: {},
                          })
                        );
                        setimagesUrl(newimageList);
                        setIndex(index);
                        setMagnifypVisible(true);
                      }}
                    >
                      <Image
                        source={{ uri: fileWeb + "/" + image.filePath }}
                        loadingIndicatorSource={require("../../../assets/interview/loading.png")}
                        style={[
                          index % 3 == 2
                            ? styles.lascolsingleimage
                            : styles.singleimage,
                          { resizeMode: "cover" },
                        ]}
                      />
                    </TouchableOpacity>
                  </View>
                );
              })}
              {/* 放大图片 */}
              <Modal visible={magnifypVisible} animationType={"fade"}>
                <ImageViewer
                  imageUrls={imagesUrl}
                  menuContext={{ saveToLocal: "保存图片", cancel: "取消" }}
                  loadingRender={Loading}
                  index={index}
                  onClick={() => {
                    setMagnifypVisible(false);
                  }}
                  onSave={() => {
                    saveImage(imagesUrl[index]);
                  }}
                />
              </Modal>
            </View>
          ) : (
            <NoData desc={"暂无图片"} type={"nopicture"} />
          )}
        </Tabs.ScrollView>
      </Tabs.Tab>
      <Tabs.Tab name="访谈录音">
        <Tabs.ScrollView
          style={{ backgroundColor: "#FFFFFF" }}
          showsVerticalScrollIndicator={false}
        >
          {dataDetail.interviewAudioList.length != 0 ? (
            <View style={styles.interviewaudio}>
              {dataDetail.interviewAudioList.map((item, index) => {
                return (
                  <AudioListItemNodelete
                    key={index}
                    audioTitle={"录音" + (index + 1)}
                    isPlaying={isPlaying}
                    activeListItem={currentAudioIndex === index}
                    onAudioPress={() => handleAudioPress(item)}
                    downloadAudio={() => saveResoure(item)}
                  />
                );
              })}
            </View>
          ) : (
            <NoData desc={"暂无录音"} type={"noaudio"} />
          )}
        </Tabs.ScrollView>
      </Tabs.Tab>
      <Tabs.Tab name="访谈视频">
        <Tabs.ScrollView
          style={{ backgroundColor: "#FFFFFF" }}
          showsVerticalScrollIndicator={false}
        >
          {dataDetail.interviewVideoList.length != 0 ? (
            <View style={styles.videoList}>
              {dataDetail.interviewVideoList.map((video, index) => {
                return (
                  <View key={index}>
                    {/* 下载视频的按钮 */}
                    <TouchableOpacity
                      onPress={() => {
                        saveVideoAlert(video);
                      }}
                      style={styles.downloadvideo}
                    >
                      <Feather
                        name="download"
                        size={19}
                        color="#ffffff"
                        style={{ zIndex: 10 }}
                      />
                    </TouchableOpacity>
                    {/* 视频列表 */}
                    <View style={{ marginBottom: 15 }}>
                      <VideoPlayer
                        videoProps={{
                          shouldPlay: false,
                          resizeMode: ResizeMode.CONTAIN,
                          source: {
                            uri: fileWeb + "/" + video.filePath,
                          },
                          ref: refVideo,
                        }}
                        style={{
                          height: inFullscreen
                            ? DEVICE_WIDTH
                            : (DEVICE_WIDTH * 3) / 5,
                          width: inFullscreen
                            ? DEVICE_HEIGHT
                            : (DEVICE_WIDTH * 4) / 5,
                          videoBackgroundColor: "#000000",
                        }}
                      />
                    </View>
                  </View>
                );
              })}
            </View>
          ) : (
            <NoData desc={"暂无视频"} type={"novideo"} />
          )}
        </Tabs.ScrollView>
      </Tabs.Tab>
    </Tabs.Container>
  );
};

export default InterviewDetail;

const styles = StyleSheet.create({
  topContainer: {
    height: DEVICE_HEIGHT / 2,
    width: "100%",
    borderBottomLeftRadius: 50,
    borderBottomRightRadius: 50,
    backgroundColor: "#A80108",
    flexDirection: "column",
    justifyContent: "space-between",
    alignContent: "center",
  },
  head: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: "100%",
    marginTop: 40,
    paddingHorizontal: 20,
  },
  fileName: {
    fontSize: 23,
    fontWeight: "bold",
    color: "#FDCE95",
    alignSelf: "center",
  },
  fileType: {
    fontSize: 14,
    color: "#FFF5E8",
    alignSelf: "center",
    marginTop: 6,
  },
  rowStyle: {
    width: (13 * DEVICE_WIDTH) / 15,
    flexDirection: "row",
    justifyContent: "space-between",
    alignContent: "center",
    marginTop: 13,
  },
  firstrowStyle: {
    width: (13 * DEVICE_WIDTH) / 15,
    flexDirection: "row",
    justifyContent: "space-between",
    alignContent: "center",
  },
  rowItem: {
    borderRadius: 20,
    paddingVertical: 8,
  },
  tagText: {
    fontSize: 14,
    color: "#FEDDB6",
    alignSelf: "center",
    marginTop: 1,
  },
  tagCount: {
    fontWeight: "bold",
    fontSize: 13,
    color: "#FFF5E8",
    alignSelf: "center",
  },
  //访谈图片位置信息
  imageList: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "flex-start",
    alignContent: "center",
    paddingHorizontal: (DEVICE_WIDTH * 3) / 40,
    paddingTop: 20,
  },
  singleimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginRight: DEVICE_WIDTH / 20,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
    backgroundColor: "#f6f6f6",
  },
  lascolsingleimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
    backgroundColor: "#f6f6f6",
  },
  videoList: {
    flexDirection: "column",
    justifyContent: "flex-start",
    alignItems: "center",
    paddingVertical: 20,
  },
  downloadvideo: {
    position: "absolute",
    zIndex: 5,
    left: 0,
    top: 0,
    backgroundColor: "#595959",
    opacity: 0.7,
    padding: 2,
  },
  ModalBackground: {
    backgroundColor: "#d5d5d5",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: DEVICE_WIDTH,
    height: DEVICE_HEIGHT,
  },
  bubblePosition: {
    position: "absolute",
    right: 17,
    zIndex: 10,
  },
  bubbleModal: {
    position: "relative",
  },
  rectangle: {
    backgroundColor: "#fff",
    paddingTop: 25,
    paddingLeft: 15,
    borderRadius: 15,
    borderTopRightRadius: 10,
    paddingRight: 20,
    zIndex: 5,
    paddingRight: 30,
  },
  rectangleText: {
    fontSize: 17,
    marginLeft: 10,
    textAlign: "center",
    textAlignVertical: "center",
    fontWeight: "bold",
    color: "#2b2b2b",
  },
  rectangleItem: {
    // backgroundColor: "yellow",
    flexDirection: "row",
    marginBottom: 25,
    zIndex: 10,
    // padding: 10,
  },
  triangle: {
    width: 0,
    height: 0,
    borderBottomWidth: 5,
    borderBottomColor: "#fff",
    borderLeftWidth: 5,
    borderLeftColor: "transparent",
    borderRightWidth: 5,
    borderRightColor: "transparent",
    position: "absolute",
    right: 10,
    top: -5,
    zIndex: 5,
  },
  interviewaudio: {
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    paddingTop: 20,
  },
});
